/**
 * 搜索引擎使用示例
 * 演示如何使用SearchEngine进行各种搜索操作
 */

import { SearchEngineImpl, createSearchEngine } from '../search-engine'
import { historyParser } from '../history-parser'
import { fileOperations } from '../file-operations'
import type { SearchOptions, ContentSearchOptions, SearchCriteria } from '../../types'

/**
 * 搜索引擎使用示例
 */
export class SearchEngineDemo {
  private searchEngine: SearchEngineImpl

  constructor() {
    // 创建搜索引擎实例
    this.searchEngine = createSearchEngine(historyParser, fileOperations)
  }

  /**
   * 初始化搜索引擎（构建索引）
   */
  async initialize(): Promise<void> {
    console.log('正在构建搜索索引...')
    const startTime = Date.now()
    
    try {
      await this.searchEngine.buildIndex()
      const duration = Date.now() - startTime
      console.log(`搜索索引构建完成，耗时: ${duration}ms`)
    } catch (error) {
      console.error('搜索索引构建失败:', error)
      throw error
    }
  }

  /**
   * 演示文件名搜索
   */
  async demonstrateFileNameSearch(): Promise<void> {
    console.log('\n=== 文件名搜索演示 ===')

    const options: SearchOptions = {
      caseSensitive: false,
      exactMatch: false,
      fileTypes: [],
      versionIds: [],
      maxResults: 10
    }

    try {
      // 搜索包含 "component" 的文件
      console.log('搜索包含 "component" 的文件:')
      const results1 = await this.searchEngine.searchByFileName('component', options)
      this.printSearchResults(results1)

      // 搜索特定文件类型
      console.log('\n搜索 Vue 文件:')
      const vueOptions = { ...options, fileTypes: ['vue'] }
      const results2 = await this.searchEngine.searchByFileName('', vueOptions)
      this.printSearchResults(results2.slice(0, 5)) // 只显示前5个结果

      // 精确匹配搜索
      console.log('\n精确匹配搜索 "App.vue":')
      const exactOptions = { ...options, exactMatch: true }
      const results3 = await this.searchEngine.searchByFileName('App.vue', exactOptions)
      this.printSearchResults(results3)

    } catch (error) {
      console.error('文件名搜索失败:', error)
    }
  }

  /**
   * 演示内容搜索
   */
  async demonstrateContentSearch(): Promise<void> {
    console.log('\n=== 内容搜索演示 ===')

    const options: ContentSearchOptions = {
      caseSensitive: false,
      exactMatch: false,
      regex: false,
      contextLines: 2,
      fileTypes: [],
      versionIds: [],
      maxResults: 5
    }

    try {
      // 搜索包含特定文本的文件
      console.log('搜索包含 "export default" 的文件:')
      const results1 = await this.searchEngine.searchByContent('export default', options)
      this.printContentSearchResults(results1)

      // 正则表达式搜索
      console.log('\n使用正则表达式搜索函数定义:')
      const regexOptions = { ...options, regex: true, fileTypes: ['js', 'ts'] }
      const results2 = await this.searchEngine.searchByContent('function\\s+\\w+', regexOptions)
      this.printContentSearchResults(results2)

      // 大小写敏感搜索
      console.log('\n大小写敏感搜索 "Vue":')
      const caseSensitiveOptions = { ...options, caseSensitive: true }
      const results3 = await this.searchEngine.searchByContent('Vue', caseSensitiveOptions)
      this.printContentSearchResults(results3)

    } catch (error) {
      console.error('内容搜索失败:', error)
    }
  }

  /**
   * 演示高级搜索
   */
  async demonstrateAdvancedSearch(): Promise<void> {
    console.log('\n=== 高级搜索演示 ===')

    try {
      // 组合条件搜索
      console.log('组合搜索 - 文件名包含 "component" 且内容包含 "Vue":')
      const criteria1: SearchCriteria = {
        fileName: 'component',
        content: 'Vue',
        fileType: 'vue'
      }
      const results1 = await this.searchEngine.advancedSearch(criteria1)
      this.printSearchResults(results1)

      // 日期范围搜索
      console.log('\n日期范围搜索 - 最近7天的文件:')
      const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
      const criteria2: SearchCriteria = {
        dateRange: {
          start: sevenDaysAgo,
          end: new Date()
        }
      }
      const results2 = await this.searchEngine.advancedSearch(criteria2)
      this.printSearchResults(results2.slice(0, 5))

      // 多条件组合搜索
      console.log('\n复杂搜索 - TypeScript文件，包含特定内容:')
      const criteria3: SearchCriteria = {
        content: 'interface',
        fileType: 'ts',
        dateRange: {
          start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // 最近30天
          end: new Date()
        }
      }
      const results3 = await this.searchEngine.advancedSearch(criteria3)
      this.printSearchResults(results3)

    } catch (error) {
      console.error('高级搜索失败:', error)
    }
  }

  /**
   * 演示搜索性能测试
   */
  async demonstratePerformanceTest(): Promise<void> {
    console.log('\n=== 搜索性能测试 ===')

    const options: SearchOptions = {
      caseSensitive: false,
      exactMatch: false,
      fileTypes: [],
      versionIds: [],
      maxResults: 100
    }

    try {
      // 单次搜索性能
      console.log('单次搜索性能测试:')
      const startTime = Date.now()
      const results = await this.searchEngine.searchByFileName('test', options)
      const duration = Date.now() - startTime
      console.log(`搜索耗时: ${duration}ms, 结果数量: ${results.length}`)

      // 并发搜索性能
      console.log('\n并发搜索性能测试:')
      const queries = ['component', 'test', 'util', 'service', 'type']
      const concurrentStart = Date.now()
      
      const promises = queries.map(query => 
        this.searchEngine.searchByFileName(query, options)
      )
      
      const concurrentResults = await Promise.all(promises)
      const concurrentDuration = Date.now() - concurrentStart
      
      console.log(`并发搜索耗时: ${concurrentDuration}ms`)
      console.log(`平均每个查询: ${Math.round(concurrentDuration / queries.length)}ms`)
      
      concurrentResults.forEach((result, index) => {
        console.log(`  "${queries[index]}": ${result.length} 个结果`)
      })

    } catch (error) {
      console.error('性能测试失败:', error)
    }
  }

  /**
   * 打印搜索结果
   */
  private printSearchResults(results: any[]): void {
    if (results.length === 0) {
      console.log('  未找到匹配的文件')
      return
    }

    results.forEach((result, index) => {
      console.log(`  ${index + 1}. ${result.fileName}`)
      console.log(`     路径: ${result.originalPath}`)
      console.log(`     版本: ${result.versionId}`)
      console.log(`     匹配分数: ${result.matchScore.toFixed(3)}`)
      console.log(`     时间: ${new Date(result.timestamp).toLocaleString()}`)
      console.log()
    })
  }

  /**
   * 打印内容搜索结果
   */
  private printContentSearchResults(results: any[]): void {
    if (results.length === 0) {
      console.log('  未找到匹配的内容')
      return
    }

    results.forEach((result, index) => {
      console.log(`  ${index + 1}. ${result.fileName}`)
      console.log(`     路径: ${result.originalPath}`)
      console.log(`     版本: ${result.versionId}`)
      console.log(`     匹配分数: ${result.matchScore.toFixed(3)}`)
      
      if (result.matches && result.matches.length > 0) {
        console.log(`     匹配内容:`)
        result.matches.slice(0, 2).forEach((match: any, matchIndex: number) => {
          console.log(`       第${match.lineNumber}行: ${match.lineContent.trim()}`)
          if (match.context && match.context.length > 1) {
            console.log(`       上下文: ${match.context.length} 行`)
          }
        })
      }
      console.log()
    })
  }

  /**
   * 运行完整演示
   */
  async runFullDemo(): Promise<void> {
    try {
      console.log('🔍 搜索引擎功能演示开始')
      console.log('================================')

      await this.initialize()
      await this.demonstrateFileNameSearch()
      await this.demonstrateContentSearch()
      await this.demonstrateAdvancedSearch()
      await this.demonstratePerformanceTest()

      console.log('\n✅ 搜索引擎功能演示完成')
      console.log('================================')

    } catch (error) {
      console.error('❌ 演示过程中发生错误:', error)
    }
  }
}

/**
 * 运行演示（如果直接执行此文件）
 */
if (require.main === module) {
  const demo = new SearchEngineDemo()
  demo.runFullDemo().catch(console.error)
}

export default SearchEngineDemo